﻿using System.Collections.Generic;

namespace Plugins.Samples.Internal
{
    using Controls;
    using Interfaces;
    
    class PiWorkItemManager
    {
        private class WorkItemData : IWorkItemData
        {
            public int Offset { get; set; }
            public int Length { get; set; }
            public string Result { get; set; }
        }

        private static List<IWorkItemData> _data = new List<IWorkItemData>();
        public static IEnumerable<IWorkItemData> Data { get { return _data; } }

        private class WorkItem : PluginWindowWorkItem<WorkItemData, PiGraphics>
        {
            private int _digits = 10000;
            private int _length = 10;

            public WorkItem(PiGraphics window)
                : base(window)
            {
            }
            public int Digits
            {
                get
                {
                    return _digits;
                }
                set
                {
                    _digits = value;
                }
            }
            public int Length
            {
                get
                {
                    return _length;
                }
                set
                {
                    _length = value;
                }
            }
            protected override int DataCount { get { return _length; } }
            protected override void InitializeData()
            {
                int length = _digits / _length;
                for (int offset = 0; offset < _digits; offset += length)
                {
                    PushData(CreateData(offset, length));
                }
            }
            protected override void ProcessData(WorkItemData data, int threadID)
            {
                if (!IsRunAsync) return;
                data.Result = PiAlgorithm.Calculate(this, this.Window, data.Offset, data.Length);
            }
        }

        public static IPluginWorkItem Create(PiGraphics window, int digits, int length)
        {
            return new WorkItem(window) { Digits = digits, Length = length };
        }

        private static WorkItemData CreateData(int offset, int length)
        {
            WorkItemData data = new WorkItemData()
            {
                Offset = offset,
                Length = length
            };
            _data.Add(data);
            return data;
        }
    }
}
